import router from '@/router'
import axios, { AxiosError, type AxiosRequestConfig } from 'axios'
import { ElLoading, ElMessage } from 'element-plus'

export const httpInstance = axios.create();

export type bkResponse = {
    data: unknown;
    code: number;
    message: string;
    succeed: true;
}

//设置请求根路径
httpInstance.defaults.baseURL = import.meta.env.VITE_BASEURL

//响应拦截器
export const $http = async (config: AxiosRequestConfig) => {
    const loadingInstance = ElLoading.service();
    try {

        const axiosResponse = await httpInstance<bkResponse>(config)
        const bkResponse = axiosResponse.data
        if (!bkResponse?.succeed) {
            let errTitle: string = 'Error'
            if (bkResponse.code === 401) {
                errTitle = 'Unauthorized'
                ElMessage.error('未授权')
            } else if (bkResponse.code === 403) {
                errTitle = 'Forbidden'
            } else if (bkResponse.code === 4001) {
                errTitle = 'JWTerror'
                ElMessage.error('未授权')
                localStorage.removeItem('token')
                router.push("/login");
            } else if (bkResponse.code === 2001) {
                errTitle = '2001Error'
                ElMessage.error('用户名或密码错误')
            } else if (bkResponse.code === 500) {
                errTitle = 'ServerError'
            } else {
                errTitle = 'Unknown'
            }
            const err = new Error(bkResponse?.message || 'Unknown')
            err.name = errTitle
            throw err
        }
        return bkResponse
    } catch (err) {
        if (err instanceof AxiosError) {
            ElMessage.error('网络错误')
        }
        throw err
    } finally {
        loadingInstance.close()
    }
}